package com.liuda066.forumssm.controller;

import com.liuda066.forumssm.common.AppResult;
import com.liuda066.forumssm.common.ResultCode;
import com.liuda066.forumssm.config.AppConfig;
import com.liuda066.forumssm.model.Article;
import com.liuda066.forumssm.model.User;
import com.liuda066.forumssm.services.IArticleService;
import com.liuda066.forumssm.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/9/4 22:41
 */
@RestController
@Slf4j
@Api(tags = "帖子测试")
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService iArticleService;

    @ApiOperation("根据板块Id查询帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllBoardId(@ApiParam(value = "板块ID") @RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> result = null;
        if (boardId == null){
            result = iArticleService.selectAll();
            log.info("查询所有帖子列表");
        }else {
            result = iArticleService.selectByBoardId(boardId);
            log.info("查询板块帖子列表,boardId : "+boardId);
        }
        if (result==null){
            result = new ArrayList<>();
        }
        return AppResult.success(result);
    }
    @ApiOperation("根据用户Id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(@ApiParam(value = "用户ID") @RequestParam(value = "userId",required = false)  Long userId){

        List<Article> result = iArticleService.selectByUserId(userId);
        log.info("查询用户帖子列表,UserId = "+userId);
        return AppResult.success(result);
    }

    @ApiOperation("根据内容查询帖子列表")
    @GetMapping("/getAllByUserContent")
    public AppResult<List<Article>> selectDetailsByContent (@ApiParam(value = "内容") @RequestParam(value = "content",required = false)  String content){
        List<Article> result = null;
        if  (content == null || StringUtils.isEmpty(content)){
            result = iArticleService.selectAll();
            log.info("查询内容帖子列表,content = "+content);
            return AppResult.success("请输入查询内容",result);
        }else {
            result = iArticleService.selectDetailsByContent(content);
            log.info("查询内容帖子列表,content = "+content);
            return AppResult.success(result);
        }

    }
    @ApiOperation("发新帖子")
    @PostMapping("/create")
    public AppResult<List<Article>> create(
            HttpServletRequest request ,
            @ApiParam(value = "板块Id") @RequestParam(value = "boardId") @NonNull Long boardId,
            @ApiParam(value = "文章标题") @RequestParam(value = "title") @NonNull String title,
            @ApiParam(value = "帖子内容") @RequestParam(value = "content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState() ==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);

        iArticleService.create(article);

        return AppResult.success();
    }

    @ApiOperation("根据Id查询帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子Id") @RequestParam(value = "id") @ NonNull Long id){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);

        Article result = iArticleService.selectDetailById(id);

        if (Objects.equals(user.getId(), result.getUserId())){
            result.setOwn(true);
        }
        return AppResult.success(result);
    }

    @ApiOperation("编辑帖子")
    @PostMapping("/modify")
    public AppResult<Article> modify(HttpServletRequest request,
                                     @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id,
                                     @ApiParam("文章标题") @RequestParam(value = "title") @NonNull String title,
                                     @ApiParam("帖子内容") @RequestParam(value = "content") @NonNull String content){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState()!=0){
            log.warn(ResultCode.FAILED_USER_BANNED.toString()+"userId : " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = iArticleService.selectDetailById(id);
        //帖子不存在
        if (article == null){
            log.warn("修改的帖子不存在,articleId = "+id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //帖子作者和当前用户不是同一人
        if (!Objects.equals(article.getUserId(), user.getId())){
            log.warn(MessageFormat.format("发帖人不是当前用户,article id = {0}, article userId = {1}, current userId = {2}"
                    ,article.getId(),article.getUserId(),user.getId()));
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //帖子状态异常
        if (article.getState() != 0 ||article.getDeleteState() != 0){
            log.warn("帖子状态异常,article id = "+article.getId()+", state = "+article.getState()+", deleteState = " + article.getDeleteState());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        iArticleService.modify(id,title,content);
        log.info(MessageFormat.format("帖子修改成功,article id = {0}, userId = {1}."
                ,article.getId(),article.getUserId()));
        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult<Article> thumbsUp(HttpServletRequest request,
                                     @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState()!=0){
            log.warn(ResultCode.FAILED_USER_BANNED.toString()+"userId : " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = iArticleService.selectDetailById(id);
        //帖子不存在
        if (article == null){
            log.warn("点赞的帖子不存在,articleId = "+id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //帖子状态异常
        if (article.getState() != 0 ||article.getDeleteState() != 0){
            log.warn("帖子状态异常,article id = "+article.getId()+", state = "+article.getState()+", deleteState = " + article.getDeleteState());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        iArticleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult<Article> deleteById(HttpServletRequest request,
                                       @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState()!=0){
            log.warn(ResultCode.FAILED_USER_BANNED.toString()+"userId : " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = iArticleService.selectDetailById(id);
        //帖子不存在
        if (article == null){
            log.warn("点赞的帖子不存在,articleId = "+id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //帖子状态异常
        if (article.getState() != 0 ||article.getDeleteState() != 0){
            log.warn("帖子状态异常,article id = "+article.getId()+", state = "+article.getState()+", deleteState = " + article.getDeleteState());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //帖子作者和当前用户不是同一人
        if (!Objects.equals(article.getUserId(), user.getId())){
            log.warn(MessageFormat.format("发帖人不是当前用户,article id = {0}, article userId = {1}, current userId = {2}"
                    ,article.getId(),article.getUserId(),user.getId()));
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        iArticleService.deleteById(id);
        return AppResult.success();
    }
}
